import orderService from "@/apis/order";
import drawQrcode from '@/utils/weapp.qrcode.min.js'

Page({
  data: {
    payment: '线上支付', // 默认线上支付
    payment_id: 0, // 默认线上支付ID
    paymentSerial: '', // 支付流水号
    paymentEvidence: '', // 凭证路径
    totalPrice: 0, // 订单总金额
    id: '',// 从父页面接收的订单ID
    qrcodeUrl: '', // 微信返回的支付二维码图片URL
    paymentTimer: null            // 用于setInterval返回的计时器ID
  },

  // 新增初始化支付方法
  async initPayment() {
    try {
      console.log(this.data.totalPrice)
      const res = await orderService.wechat_pay(this.data.id, this.data.totalPrice);
      if (res.data.code == 200) {
        // 绘制二维码（网页3、网页6、网页8示例）
        drawQrcode({
          width: 200,       // 画布宽度（单位：px）
          height: 200,      // 画布高度
          canvasId: 'payQrcode', // 与 wxml 中 canvas-id 一致
          text: res.data.qrcode_url,     // 支付码内容
          correctLevel: 0   // 纠错级别（0-3，默认0）
        });
        this.startPaymentCheck();
      }
    } catch (error) {
      console.log(error)
      wx.showToast({ title: error, icon: 'none' });
    }
  },
  // 启动支付状态检查
  startPaymentCheck() {
    this.data.paymentTimer = setInterval(async () => {
      const res = await orderService.check_pay_status(this.data.id);
      console.log(res)
      if (res.data.paid) {
        clearInterval(this.data.paymentTimer);
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000
        });
        setTimeout(() => {
          //跳转到订单列表页面
          wx.switchTab({
            url: '/pages/order/list/list',
          })
        }, 2000);
      }
    }, 3000);
  },

  onLoad(options) {
    const app = getApp()
    wx.setKeepScreenOn({
      keepScreenOn: app.globalData.isRecording,
      success: () => console.log('常亮已启用')
    });
    console.log(options)
    this.setData({
      id: options.id, // 接收订单ID
      payment: options.payment,
      payment_id: options.payment_id,
      totalPrice: options.total
    });
    this.initPayment();
  },
  onUnload() {
    const app = getApp()
    wx.setKeepScreenOn({
      keepScreenOn: app.globalData.isRecording,
      success: () => console.log('常亮已启用')
    });
    if (this.data.paymentTimer) {
      clearInterval(this.data.paymentTimer);
    }
  },
  onShow() {
    const app = getApp();
    app.checkToken().then(valid => {
      console.log("order/list.js onShow() token验证结果: " + valid);
    });
  },

  // 输入流水号
  bindSerialInput(e) {
    this.setData({ paymentSerial: e.detail.value });
  },

  chooseImage(e) {
    const { fieldname, tempFilePath } = e.detail;
    this.setData({ [fieldname]: tempFilePath })
  },
  removeImage(e) {
    const { fieldname } = e.detail;
    this.setData({ [fieldname]: '' })
  },

  // 预览凭证
  previewImage() {
    wx.previewImage({
      current: this.data.paymentEvidence,
      urls: [this.data.paymentEvidence]
    });
  },

  // 提交线下支付
  async handleOfflinePayment() {
    const { id, payment, payment_id, paymentSerial, paymentEvidence } = this.data;

    if (!paymentSerial) {
      wx.showToast({ title: '请输入流水号', icon: 'none' });
      return;
    }

    if (!paymentEvidence) {
      wx.showToast({ title: '请上传支付凭证', icon: 'none' });
      return;
    }
    const app = getApp()
    app.globalData.recorderManager.stop();

    wx.showLoading({ title: '提交中...' });

    try {
      // 将图片转换为base64
      const proofBase64 = wx.getFileSystemManager().readFileSync(paymentEvidence, 'base64');

      // 调用提交接口
      const res = await orderService.pay({
        id: id,
        payment_id,
        payment,
        payment_serial: paymentSerial,
        payment_evidence: `data:image/png;base64,${proofBase64}`
      });

      wx.hideLoading();
      wx.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 1500,
        success: () => {
          //跳转到订单列表页面
          wx.switchTab({
            url: '/pages/order/list/list',
          })
        }
      });
      setTimeout(() => {
        //跳转到订单列表页面
        wx.switchTab({
          url: '/pages/order/list/list',
        })
      }, 1500);
    } catch (err) {
      console.log(err)
      wx.hideLoading();
      wx.showToast({ title: '提交失败', icon: 'none' });
    }
  }
});